package com.fafa.File;

import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileWriteOrRead {
    public static void main(String[] args) {

    }


    /**
     * 单个字节读取，效率较低
     */
    @Test
    public void readFile() {
        File filePath = new File("E:\\news1.txt");
        FileInputStream fileInputStream = null;
        int readDate = 0;
        try {
            fileInputStream = new FileInputStream(filePath);
            //反复读取
            while((readDate = fileInputStream.read()) != -1)
            {
                System.out.print((char)readDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭释放
            if( fileInputStream != null)
            {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }
    /**
     * 优化版本，提高效率
     * 读取到字符串中
     */
    //移除警告
    @SuppressWarnings("all")
    @Test
    public void readFile1() {
        File filePath = new File("E:\\news1.txt");
        FileInputStream fileInputStream = null;
        int readLen = 0;
        byte[] buf = new byte[8];
        try {
            fileInputStream = new FileInputStream(filePath);
            //反复读取
            while((readLen = fileInputStream.read(buf)) != -1)
            {
                //public String(byte[] data, int start, int length)
                System.out.print(new String(buf,0,readLen));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //关闭释放
            if( fileInputStream != null)
            {
                try {
                    fileInputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }


    }

    @Test
    public void writeFile() {
        File filePath = new File("E:\\news1.txt");
        FileOutputStream fileOutputStream = null;
        byte[] buf = "Hello World".getBytes();
        try {
            //覆盖填充
            //fileOutputStream = new FileOutputStream(filePath);
            //追加到文件末尾
            fileOutputStream = new FileOutputStream(filePath, true);
            fileOutputStream.write(buf);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
        finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

}

